package com.cskaoyan.salary;

import com.cskaoyan.salary.bean.Employee;
import com.cskaoyan.salary.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/employeeList")
public class EmployeeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DataSource dataSource = DruidUtils.getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        List<Employee> employeeList = null;
        try {
            employeeList = queryRunner.query("select * from t_employee", new BeanListHandler<>(Employee.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

//        try {
//            connection = JDBCUtils.getConnection();
//            preparedStatement = connection.prepareStatement("select * from t_employee;");
//            resultSet = preparedStatement.executeQuery();
//            while (resultSet.next()){
//                int id = resultSet.getInt("id");
//                String name = resultSet.getString("name");
//                double salary = resultSet.getDouble("salary");
//                Employee employee = new Employee(id, name, salary);
//                employeeList.add(employee);
//            }
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (SQLException throwables) {
//            throwables.printStackTrace();
//        } finally {
//            try {
//                JDBCUtils.releaseResources(connection,resultSet,preparedStatement);
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
//        }
        //复制一份查询结果，筛除boss
        ArrayList<Employee> employeenoBossList = new ArrayList<>(employeeList);
        for (int i = 0; i < employeenoBossList.size(); i++) {
            if (employeenoBossList.get(i).getName().equals("boss")){
                employeenoBossList.remove(i);
            }
        }
        //将员工薪水信息传到request域(没有老板)
        //将所有人员信息放在session域
        request.setAttribute("employeenoBossList",employeenoBossList);
        request.getSession().setAttribute("employeeList",employeeList);
        //转到发工资页面
        request.getRequestDispatcher("/employeeList.jsp").forward(request, response);

    }
}
